package com.qf.servlet;

import com.qf.entity.Emp;
import com.qf.service.EmpService;
import com.qf.service.impl.EmpServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zdl
 * @date 2025/1/16
 */
@WebServlet("/update")
public class UpdateEmpServlet extends HttpServlet {
    private EmpService empService = new EmpServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        Emp emp = empService.findEmp(Integer.parseInt(id));
        PrintWriter out = resp.getWriter();
        out.write("<html>");
        out.write("<body>");
        out.write("<form action='/update?id="+Integer.parseInt(id)+"' method='post'>");
        out.write("姓名:<input type = 'text' name = 'username' value = "+emp.getName()+">");
        out.write("年龄:<input type = 'text' name = 'age' value = "+emp.getAge()+">");
        out.write("性别: <input type='radio' name='sex' value='男' " + ("男".equals(emp.getSex()) ? "checked" : "") + "> 男 ");
        out.write("<input type='radio' name='sex' value='女' " + ("女".equals(emp.getSex()) ? "checked" : "") + "> 女 ");
        out.write("余额:<input type = 'text' name = 'salary' value = "+emp.getSalary()+">");
        out.write("<input type = 'submit' value = '确认修改'>");
        out.write("<form>");
        out.write("</body>");
        out.write("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        int i = Integer.parseInt(id);
        String username = req.getParameter("username");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String salary = req.getParameter("salary");
        Emp emp = new Emp(i, username, Integer.parseInt(age), sex, Double.parseDouble(salary));
        int i1 = empService.updateEmp(emp);
        if (i1 > 0){
            resp.sendRedirect("/list");
        }
    }
}
